package com.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tc.domain.Drugs_info;
import com.tc.domain.Insured_person;
import com.tc.domain.Patient_drug_order;
import com.tc.dto.Patient_drug_orderDTO;
import com.tc.dto.Patient_drug_orderQueryDTO;
import com.tc.mapper.Drugs_infoMapper;
import com.tc.mapper.Insured_personMapper;
import com.tc.mapper.Patient_drug_orderMapper;
import com.tc.service.IPatient_drug_orderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tc.vo.PageResultVO;
import com.tc.vo.Patient_drug_orderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  患者药品医嘱服务实现类
 * </p>
 *
 * @author jcd
 * @since 2025-07-09
 */
@Service
public class Patient_drug_orderServiceImpl extends ServiceImpl<Patient_drug_orderMapper, Patient_drug_order> implements IPatient_drug_orderService {

    @Autowired
    private Drugs_infoMapper drugsInfoMapper;
    
    @Autowired
    private Insured_personMapper insuredPersonMapper;

    @Override
    public PageResultVO<Patient_drug_orderVO> pageQuery(Patient_drug_orderQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<Patient_drug_order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (queryDTO.getPatientId() != null) {
            queryWrapper.eq(Patient_drug_order::getPatientId, queryDTO.getPatientId());
        }
        
        if (queryDTO.getDoctorId() != null) {
            queryWrapper.eq(Patient_drug_order::getDoctorId, queryDTO.getDoctorId());
        }
        
        // 处理时间范围查询
        if (StringUtils.hasText(queryDTO.getStartTime()) && StringUtils.hasText(queryDTO.getEndTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(queryDTO.getStartTime(), formatter);
            LocalDateTime endTime = LocalDateTime.parse(queryDTO.getEndTime(), formatter);
            queryWrapper.between(Patient_drug_order::getOrderTime, startTime, endTime);
        } else if (StringUtils.hasText(queryDTO.getStartTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(queryDTO.getStartTime(), formatter);
            queryWrapper.ge(Patient_drug_order::getOrderTime, startTime);
        } else if (StringUtils.hasText(queryDTO.getEndTime())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime endTime = LocalDateTime.parse(queryDTO.getEndTime(), formatter);
            queryWrapper.le(Patient_drug_order::getOrderTime, endTime);
        }
        
        // 药品名称模糊查询需要先查找药品信息
        if (StringUtils.hasText(queryDTO.getDrugName())) {
            LambdaQueryWrapper<Drugs_info> drugsQueryWrapper = new LambdaQueryWrapper<>();
            drugsQueryWrapper.like(Drugs_info::getDrugName, queryDTO.getDrugName())
                    .or()
                    .like(Drugs_info::getTradeName, queryDTO.getDrugName());
            List<Drugs_info> drugsList = drugsInfoMapper.selectList(drugsQueryWrapper);
            if (drugsList != null && !drugsList.isEmpty()) {
                List<Long> drugIds = drugsList.stream()
                        .map(Drugs_info::getDrugId)
                        .collect(Collectors.toList());
                queryWrapper.in(Patient_drug_order::getDrugId, drugIds);
            } else {
                // 如果没有找到匹配的药品，则返回空结果
                PageResultVO<Patient_drug_orderVO> emptyResult = new PageResultVO<>();
                emptyResult.setTotal(0L);
                emptyResult.setCurrent((long) queryDTO.getPageNum());
                emptyResult.setSize((long) queryDTO.getPageSize());
                emptyResult.setPages(0L);
                emptyResult.setRecords(new ArrayList<>());
                return emptyResult;
            }
        }
        // 药品类型查询
        if(StringUtils.hasText(queryDTO.getClassification())){

            LambdaQueryWrapper<Drugs_info> drugsQueryWrapper = new LambdaQueryWrapper<>();
            drugsQueryWrapper.eq(Drugs_info::getClassification, queryDTO.getClassification());
            List<Drugs_info> drugsList = drugsInfoMapper.selectList(drugsQueryWrapper);
            if (drugsList != null && !drugsList.isEmpty()) {
                List<Long> drugIds = drugsList.stream()
                        .map(Drugs_info::getDrugId)
                        .collect(Collectors.toList());
                queryWrapper.in(Patient_drug_order::getDrugId, drugIds);
            } else {
                // 如果没有找到匹配的药品，则返回空结果
                PageResultVO<Patient_drug_orderVO> emptyResult = new PageResultVO<>();
                emptyResult.setTotal(0L);
                emptyResult.setCurrent((long) queryDTO.getPageNum());
                emptyResult.setSize((long) queryDTO.getPageSize());
                emptyResult.setPages(0L);
                emptyResult.setRecords(new ArrayList<>());
                return emptyResult;
            }
            
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Patient_drug_order::getOrderTime);
        
        // 执行分页查询
        Page<Patient_drug_order> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<Patient_drug_order> resultPage = this.page(page, queryWrapper);
        
        // 转换为VO列表
        List<Patient_drug_orderVO> records = convertToVOList(resultPage.getRecords());
        
        // 使用PageResultVO的静态方法直接构建分页结果对象
        return PageResultVO.convert(resultPage, records);
    }

    @Override
    public List<Patient_drug_orderVO> getByPatientId(Long patientId) {
        LambdaQueryWrapper<Patient_drug_order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Patient_drug_order::getPatientId, patientId);
        queryWrapper.orderByDesc(Patient_drug_order::getOrderTime);
        
        List<Patient_drug_order> list = this.list(queryWrapper);
        return convertToVOList(list);
    }

    @Override
    public Patient_drug_orderVO getPatientDrugOrderById(Long id) {
        Patient_drug_order patientDrugOrder = this.getById(id);
        if (patientDrugOrder == null) {
            return null;
        }
        
        // 获取药品信息
        Drugs_info drugsInfo = drugsInfoMapper.selectById(patientDrugOrder.getDrugId());
        
        // 获取患者信息
        Insured_person patient = insuredPersonMapper.selectById(patientDrugOrder.getPatientId());
        
        // 构建VO
        Patient_drug_orderVO vo = new Patient_drug_orderVO();
        BeanUtils.copyProperties(patientDrugOrder, vo);
        
        if (drugsInfo != null) {
            vo.setDrugName(drugsInfo.getDrugName());
            vo.setTradeName(drugsInfo.getTradeName());
            vo.setSpecification(drugsInfo.getSpecification());
            vo.setUnit(drugsInfo.getUnit());
            vo.setPaymentStandard(drugsInfo.getPaymentStandard());
            
            // 计算总金额
            if (drugsInfo.getPaymentStandard() != null && patientDrugOrder.getQuantity() != null) {
                vo.setTotalAmount(drugsInfo.getPaymentStandard().multiply(new BigDecimal(patientDrugOrder.getQuantity())));
            }
        }
        
        if (patient != null) {
            vo.setPatientName(patient.getName());
        }
        
        return vo;
    }

    @Override
    @Transactional
    public boolean addPatientDrugOrder(Patient_drug_orderDTO patientDrugOrderDTO) {
        Patient_drug_order patientDrugOrder = new Patient_drug_order();
        BeanUtils.copyProperties(patientDrugOrderDTO, patientDrugOrder);
        
        // 设置开具时间，如果为空则使用当前时间
        if (patientDrugOrder.getOrderTime() == null) {
            patientDrugOrder.setOrderTime(LocalDateTime.now());
        }
        
        // 设置逻辑删除标志为未删除
        patientDrugOrder.setDeleted(0);
        
        return this.save(patientDrugOrder);
    }

    @Override
    @Transactional
    public boolean updatePatientDrugOrder(Patient_drug_orderDTO patientDrugOrderDTO) {
        Patient_drug_order patientDrugOrder = new Patient_drug_order();
        BeanUtils.copyProperties(patientDrugOrderDTO, patientDrugOrder);
        
        return this.updateById(patientDrugOrder);
    }

    @Override
    @Transactional
    public boolean deletePatientDrugOrder(Long id) {
        return this.removeById(id);
    }
    
    /**
     * 将实体对象列表转换为视图对象列表
     * @param list 实体对象列表
     * @return 视图对象列表
     */
    private List<Patient_drug_orderVO> convertToVOList(List<Patient_drug_order> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取所有药品ID
        List<Long> drugIds = list.stream()
                .map(Patient_drug_order::getDrugId)
                .distinct()
                .collect(Collectors.toList());
        
        // 获取所有患者ID
        List<Long> patientIds = list.stream()
                .map(Patient_drug_order::getPatientId)
                .distinct()
                .collect(Collectors.toList());
        
        // 批量查询药品信息
        LambdaQueryWrapper<Drugs_info> drugsQueryWrapper = new LambdaQueryWrapper<>();
        drugsQueryWrapper.in(Drugs_info::getDrugId, drugIds);
        List<Drugs_info> drugsList = drugsInfoMapper.selectList(drugsQueryWrapper);
        Map<Long, Drugs_info> drugsMap = drugsList.stream()
                .collect(Collectors.toMap(Drugs_info::getDrugId, drug -> drug));
        
        // 批量查询患者信息
        LambdaQueryWrapper<Insured_person> patientQueryWrapper = new LambdaQueryWrapper<>();
        patientQueryWrapper.in(Insured_person::getPatientId, patientIds);
        List<Insured_person> patientList = insuredPersonMapper.selectList(patientQueryWrapper);
        Map<Long, Insured_person> patientMap = patientList.stream()
                .collect(Collectors.toMap(Insured_person::getPatientId, patient -> patient));
        
        // 转换为VO列表
        return list.stream().map(entity -> {
            Patient_drug_orderVO vo = new Patient_drug_orderVO();
            BeanUtils.copyProperties(entity, vo);
            
            // 设置药品信息
            Drugs_info drugsInfo = drugsMap.get(entity.getDrugId());
            if (drugsInfo != null) {
                vo.setDrugName(drugsInfo.getDrugName());
                vo.setClassification(drugsInfo.getClassification());
                vo.setTradeName(drugsInfo.getTradeName());
                vo.setSpecification(drugsInfo.getSpecification());
                vo.setUnit(drugsInfo.getUnit());
                vo.setPaymentStandard(drugsInfo.getPaymentStandard());
                
                // 计算总金额
                if (drugsInfo.getPaymentStandard() != null && entity.getQuantity() != null) {
                    vo.setTotalAmount(drugsInfo.getPaymentStandard().multiply(new BigDecimal(entity.getQuantity())));
                }
            }
            
            // 设置患者信息
            Insured_person patient = patientMap.get(entity.getPatientId());
            if (patient != null) {
                vo.setPatientName(patient.getName());
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
}
